package info.maxhis.service;

import info.maxhis.entity.Friend;
import info.maxhis.util.CalendarUtil;
import info.maxhis.util.DBTool;
import info.maxhis.util.GoogleCalendarUtil;
import info.maxhis.util.SharedData;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.Environment;
import android.widget.Toast;

/**
 * 服务类
 * @author iStar
 *
 */
public class FriendService {
	private DBTool db;
	private SharedData share;
	private GoogleCalendarUtil googleCalendar;
	private Context context;
	
	public FriendService(Context context) {
		this.context = context;
		db = new DBTool(context);
		share = new SharedData(context);
		googleCalendar = new GoogleCalendarUtil(context);
	}
	
	/**
	 * 添加朋友生日信息
	 * @param friend	朋友实体
	 * @return	添加是否成功
	 */
	public boolean addFriend(Friend friend){
		ContentValues value = new ContentValues();
		value.put("name", friend.getName());
		value.put("year", friend.getBirthYear());
		value.put("month", friend.getBirthMonth());
		value.put("day", friend.getBirthDay());
		value.put("dateType", friend.getDateType());
		value.put("uid", friend.getUid());
		value.put("headurl", friend.getHeadurl());
		value.put("phone", friend.getPhone());
		if(db.isClosed()) db.open();
		long count = db.insert("friend", null, value );
		db.close();
		
		return (count > 0);
	}
	
	/**
	 * 添加到Google Calendar
	 * @param friend
	 * @return
	 */
	public boolean addToGoogle(Friend friend) {
		boolean flag = false;
		
		//添加到Google Calendar
		Calendar recentBirthday = null;
		Calendar now = Calendar.getInstance(); 
		if (share.isSyncGoogleCalendar()) {
			//将农历转换成公历
			try {
				if (CalendarUtil.DATE_TYPE_LUNDAR == friend.getDateType()) {
					recentBirthday = CalendarUtil.toSolarCalendar(now.get(Calendar.YEAR), 
							friend.getBirthMonth(), friend.getBirthDay());
				} else {
					recentBirthday = new GregorianCalendar(now.get(Calendar.YEAR), 
							friend.getBirthMonth()-1, friend.getBirthDay());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			//如果今年生日已过则不添加
			if (recentBirthday.after(now)) {
				googleCalendar.addToGoogleCalendar(friend.getName(), recentBirthday);
				flag = true;
			}
		}
		
		return flag;
	}
	
	/**
	 * 删除朋友生日信息
	 * @param friend
	 * @return	是否删除成功
	 */
	public boolean removeFriend(Friend friend){
		int id = friend.getId();
		if(db.isClosed()) db.open();
		long count = db.delete("friend", "_id=?", new String[]{""+id});
		db.close();
		return count > 0;
	}
	
	/**
	 * 根据姓名查找朋友
	 * @param name
	 * @return	查找到的朋友，没有找到返回null
	 */
	public ArrayList<Friend> findFriendByName(String name){
		ArrayList<Friend> friends = null;
		if(db.isClosed()) db.open();
//		Cursor cursor = db.queryWhere("friend", "name=?", new String[]{name}, null);
		//模糊查找
		Cursor cursor = db.querySql("select * from friend where name like '%"+name+"%'", null);
		if (cursor != null) {
			friends = new ArrayList<Friend>();
			for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
				String phone = cursor.getString(cursor.getColumnIndex("phone"));
				String nickName = cursor.getString(cursor.getColumnIndex("name"));
				int id = cursor.getInt(cursor.getColumnIndex("_id"));
				int year = cursor.getInt(cursor.getColumnIndex("year"));
				int month = cursor.getInt(cursor.getColumnIndex("month"));
				int day = cursor.getInt(cursor.getColumnIndex("day"));
				int dateType = cursor.getInt(cursor.getColumnIndex("dateType"));
				Friend friend = new Friend(nickName, year, month, day);
				friend.setId(id);
				friend.setDateType(dateType);
				friend.setPhone(phone);
				friends.add(friend);
			}
		}
		db.close();
		return friends;
	}
	
	/**
	 * 查找所有朋友信息
	 * @return	已经添加的所有朋友生日信息
	 */
	public ArrayList<Friend> getAllFriends(){
		ArrayList<Friend> friends = null;
		if(db.isClosed()) db.open();
		Cursor cursor = db.getAllData("friend");
		if (cursor != null) {
			friends = new ArrayList<Friend>();
			for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
				String name = cursor.getString(cursor.getColumnIndex("name"));
				String phone = cursor.getString(cursor.getColumnIndex("phone"));
				int id = cursor.getInt(cursor.getColumnIndex("_id"));
				int year = cursor.getInt(cursor.getColumnIndex("year"));
				int month = cursor.getInt(cursor.getColumnIndex("month"));
				int day = cursor.getInt(cursor.getColumnIndex("day"));
				int dateType = cursor.getInt(cursor.getColumnIndex("dateType"));
				String uid = cursor.getString(cursor.getColumnIndex("uid"));
				Friend friend = new Friend(name, year, month, day);
				friend.setId(id);
				friend.setDateType(dateType);
				friend.setPhone(phone);
				friend.setUid(uid);
				friends.add(friend);
			}
		}
		db.close();
		return friends;
	}
	
	/**
	 * 修改朋友生日信息
	 * @param friend
	 * @return
	 */
	public boolean updateFriend(Friend friend){
		ContentValues value = new ContentValues();
		value.put("name", friend.getName());
		value.put("year", friend.getBirthYear());
		value.put("month", friend.getBirthMonth());
		value.put("day", friend.getBirthDay());
		value.put("dateType", friend.getDateType());
		value.put("phone", friend.getPhone());
		if(db.isClosed()) db.open();
		long count = db.update("friend", value, "_id=?", new String[]{friend.getId()+""});
		db.close();
		return count > 0;
	}
	
	/**
	 * 根据ID查找Friend
	 * @param fId
	 * @return
	 */
	public Friend findFriendById(String fId) {
		Friend friend = null;
		if(db.isClosed()) db.open();
		Cursor cursor = db.queryWhere("friend", "_id=?", new String[]{fId}, null);
		if (cursor != null) {
			cursor.moveToFirst();
			String name = cursor.getString(cursor.getColumnIndex("name"));
			String phone = cursor.getString(cursor.getColumnIndex("phone"));
			int id = cursor.getInt(cursor.getColumnIndex("_id"));
			int year = cursor.getInt(cursor.getColumnIndex("year"));
			int month = cursor.getInt(cursor.getColumnIndex("month"));
			int day = cursor.getInt(cursor.getColumnIndex("day"));
			int dateType = cursor.getInt(cursor.getColumnIndex("dateType"));
			friend = new Friend(name, year, month, day);
			friend.setId(id);
			friend.setDateType(dateType);
			friend.setPhone(phone);
		}
		db.close();
		return friend;
	}
	
	/**
	 * 查找最近过生日的朋友，主要考虑农历与公历的差别
	 * @return
	 */
	public ArrayList<Friend> getRecentFriends() {
		ArrayList<Friend> friends = null;
		if(db.isClosed()) db.open();
		int m = Calendar.getInstance().get(Calendar.MONTH)+1;
		Cursor cursor = db.querySql("select * from friend where month >= ? and month <=?"
				, new String[]{""+(m - 3),""+m});
		if (cursor != null) {
			friends = new ArrayList<Friend>();
			for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
				String name = cursor.getString(cursor.getColumnIndex("name"));
				String phone = cursor.getString(cursor.getColumnIndex("phone"));
				int id = cursor.getInt(cursor.getColumnIndex("_id"));
				int year = cursor.getInt(cursor.getColumnIndex("year"));
				int month = cursor.getInt(cursor.getColumnIndex("month"));
				int day = cursor.getInt(cursor.getColumnIndex("day"));
				int dateType = cursor.getInt(cursor.getColumnIndex("dateType"));
				Friend friend = new Friend(name, year, month, day);
				friend.setId(id);
				friend.setDateType(dateType);
				friend.setPhone(phone);
				friends.add(friend);
			}
		}
		db.close();
		return friends;
	}
	
	/**
	 * 返回生日在from和to之间的朋友列表
	 * @param from 	格式为MM-dd
	 * @param to	格式为MM-dd
	 * @return
	 */
	public ArrayList<Friend> getFriends(String from, String to) {
		String[] fromArr = from.split("-");
		String[] toArr = to.split("-");
		long fromMills = CalendarUtil.getMills(Integer.parseInt(fromArr[0]),Integer.parseInt(fromArr[1]));
		long toMills = CalendarUtil.getMills(Integer.parseInt(toArr[0]),Integer.parseInt(toArr[1]));
		ArrayList<Friend> friends = null;
		if(db.isClosed()) db.open();
		Cursor cursor = db.querySql("select * from friend where month >= ? and month <=?"
				, new String[]{fromArr[0],toArr[0]});//缩小范围
		if (cursor != null) {
			friends = new ArrayList<Friend>();
			for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
				String name = cursor.getString(cursor.getColumnIndex("name"));
				String phone = cursor.getString(cursor.getColumnIndex("phone"));
				int id = cursor.getInt(cursor.getColumnIndex("_id"));
				int year = cursor.getInt(cursor.getColumnIndex("year"));
				int month = cursor.getInt(cursor.getColumnIndex("month"));
				int day = cursor.getInt(cursor.getColumnIndex("day"));
				int dateType = cursor.getInt(cursor.getColumnIndex("dateType"));
				Friend friend = new Friend(name, year, month, day);
				friend.setId(id);
				friend.setDateType(dateType);
				friend.setPhone(phone);
				long fMills = CalendarUtil.getMills(friend.getBirthMonth(),friend.getBirthDay());
				if (fMills >= fromMills && fMills <= toMills) {
					friends.add(friend);
				}
			}
		}
		db.close();
		return friends;
	}
	
	/**
	 * 判断是否已经添加到本地
	 * @param uid 人人网uid
	 * @return	true 已添加	, false 未添加
	 */
	public boolean friendExsited(String uid) {
		boolean exsited = false;
		if(db.isClosed()) db.open();
		Cursor cursor = db.queryWhere("friend", "uid=?", new String[]{uid}, null);
		if (cursor != null && cursor.getCount() > 0) {
			 exsited = true;
		}
		db.close();
		return exsited;
	}
	
	/**
	 * 保存头像到本地
	 * @param context
	 * @param url
	 * @param f
	 */
	public void saveFriendHead(String path,String fileName){
		File dir = new File(Environment.getExternalStorageDirectory()+"/birthday/head");
		File file = new File(dir,fileName+".jpg");
		if (!dir.exists()) {
			dir.mkdirs();  //创建文件目录
		}
		if (file.exists()) {
			return ;	//不重复保存
		}
		try {
			URL url = new URL(path);
			InputStream is = url.openStream();
			FileOutputStream fos = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int len = -1;
			while ((len = is.read(buffer)) != -1) {
				fos.write(buffer,0,len);
			}
			is.close();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
